# _*_ coding:utf-8 _*_

#@Time :2020/8/23 

# @Author : litao

# @File : orm.py
from utils.LoggerUtil import logger
import aiomysql
import aiopg
import sys

def log(sql, args=()):
    if sys.getsizeof(args) > 50:
        logger.debug('SQL: {}'.format(sql))
        return
    logger.debug('SQL: {}, args: {}'.format(sql, args))

async def create_pool(**kw):
    global __pool
    logger.info('create database connection...')
    logger.info('password={}'.format(kw['password']))
    __pool = await aiomysql.create_pool(
        host=kw.get('host', 'localhost'),
        port=kw.get('port', 3306),
        user=kw['user'],
        password=kw['password'],
        db=kw['db'],
        charset=kw.get('charset', 'utf8'),
        autocommit=kw.get('autocommit', True),
        maxsize=kw.get('maxsize', 10),
        minsize=kw.get('minsize', 1),

    )


    # try:
    #     with (await __pool) as conn:
    #         cur = await conn.cursor(aiomysql.DictCursor)
    #         await cur.execute("SELECT COUNT(*) FROM entries LIMIT 1")
    #         await cur.fetchone()
    # except :
    #     print("project.sql")
    #     with open("project.sql") as f:
    #         schema = f.read()
    #     print(schema)
    #     with (await __pool) as conn:
    #         cur = await conn.cursor(aiomysql.DictCursor)
    #         await cur.execute(schema)

async def create_pg_pool(**kw):
    global __pool
    print(kw)
    logger.info('create database connection...')
    __pool = await aiopg.create_pool(
        host=kw.get('host', 'localhost'),
        port=kw.get('port', 3306),
        user=kw['user'],
        password=kw['password'],
        dbname=kw['db'],
    )
    try:
        print(int('10.1'))
        with (await __pool.cursor()) as cur:

            await cur.execute("SELECT COUNT(*) FROM entries LIMIT 1")
            await cur.fetchone()
    except:
        print("project_pg.sql")
        with open("project_pg.sql") as f:
            schema = f.read()
        print(schema)
        with (await __pool.cursor()) as cur:
            await cur.execute(schema)

async def select(sql, args, size=None):
    log(sql, args)
    global __pool
    log(__pool)
    with (await __pool) as conn:
        cur = await conn.cursor(aiomysql.DictCursor)
        await cur.execute(sql.replace('?', '%s'), args or ())
        if size:
            rs = await cur.fetchmany(size)
        else:
            rs = await cur.fetchall()
        await cur.close()
        logger.info('rows returned: %s' % len(rs))
        return rs

async def execute(sql, args):
    log(sql, args)
    global __pool
    with (await __pool) as conn:
        affected = 0
        try:
            cur = await conn.cursor()
            await cur.execute(sql.replace('?', '%s'), args)
            affected = cur.rowcount
            await cur.close()
        except BaseException as e:
            logger.error('ERROR:'+str(e))
            await conn.rollback()
        return affected

def create_args_string(num):
    L = []
    for n in range(num):
        L.append('?')
    return ', '.join(L)

class ModelMetaclass(type):
    def __new__(cls, name, bases, attrs):
        # 排除Model类本身:
        if name=='Model':
            return type.__new__(cls, name, bases, attrs)
        # 获取table名称:
        tableName = attrs.get('__table__', None) or name
        logger.info('found model: %s (table: %s)' % (name, tableName))
        # 获取所有的Field和主键名:
        mappings = dict()
        fields = []
        primaryKey = None
        for k, v in attrs.items():
            if isinstance(v, Field):
                logger.info('  found mapping: %s ==> %s' % (k, v))
                mappings[k] = v
                if v.primary_key:
                    # 找到主键:
                    if primaryKey:
                        raise RuntimeError('Duplicate primary key for field: %s' % k)
                    primaryKey = k
                else:
                    fields.append(k)
        if not primaryKey:
            raise RuntimeError('Primary key not found.')
        for k in mappings.keys():
            attrs.pop(k)
        escaped_fields = list(map(lambda f: '`%s`' % f, fields))
        attrs['__mappings__'] = mappings # 保存属性和列的映射关系
        attrs['__table__'] = tableName
        attrs['__primary_key__'] = primaryKey # 主键属性名
        attrs['__fields__'] = fields # 除主键外的属性名
        # 构造默认的SELECT, INSERT, UPDATE和DELETE语句:
        attrs['__select__'] = 'select `%s`, %s from `%s`' % (primaryKey, ', '.join(escaped_fields), tableName)
        attrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s)' % (tableName, ', '.join(escaped_fields), primaryKey, create_args_string(len(escaped_fields) + 1))
        attrs['__update__'] = 'update `%s` set %s where `%s`=?' % (tableName, ', '.join(map(lambda f: '`%s`=?' % (mappings.get(f).name or f), fields)), primaryKey)
        attrs['__delete__'] = 'delete from `%s` where `%s`=?' % (tableName, primaryKey)
        return type.__new__(cls, name, bases, attrs)

class Model(dict, metaclass=ModelMetaclass):

    def __init__(self, **kw):
        super(Model, self).__init__(**kw)

    def __getattr__(self, key):

        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Model' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value

    def getValue(self, key):
        return getattr(self, key, None)

    def getValueOrDefault(self, key):

        value = getattr(self, key, None)
        if value is None:
            field = self.__mappings__[key]
            if field.default is not None:
                value = field.default() if callable(field.default) else field.default
                logger.debug('using default value for %s: %s' % (key, str(value)))
                setattr(self, key, value)
        return value

    @classmethod
    async def findAll(cls, where=None, args=None, **kw):
        ## find objects by where clause
        sql = [cls.__select__]
        if where:
            sql.append('where')
            sql.append(where)
        if args is None:
            args = []
        orderBy = kw.get('orderBy', None)
        if orderBy:
            sql.append('order by')
            sql.append(orderBy)
        limit = kw.get('limit', None)
        if limit is not None:
            sql.append('limit')
            if isinstance(limit, int):
                sql.append('?')
                args.append(limit)
            elif isinstance(limit, tuple) and len(limit) == 2:
                sql.append('?, ?')
                args.extend(limit)
            else:
                raise ValueError('Invalid limit value: %s' % str(limit))
        rs = await select(' '.join(sql), args)
        return [cls(**r) for r in rs]

    @classmethod
    async def findNumber(cls, selectField, where=None, args=None):
        ## find number by select and where

        sql = ['select %s _num_ from `%s`' % (selectField, cls.__table__)]
        logger.info('sql={}'.format(sql))
        if where:
            sql.append('where')
            sql.append(where)
        logger.info('sql1={}'.format(' '.join(sql)))
        rs = await select(' '.join(sql), args, 1)
        if len(rs) == 0:
            return None
        logger.info('rs={}'.format(rs))
        return rs[0]['_num_']

    @classmethod
    async def find(cls, pk):
        ## find object by primary key
        #logger.info('【'+'%s where `%s`=?' % (cls.__select__, cls.__primary_key__)+'】')
        rs = await select('%s where `%s`=?' % (cls.__select__, cls.__primary_key__), [pk], 1)
        if len(rs) == 0:
            return None
        return cls(**rs[0])

    @classmethod
    async def findbyindex(cls, **kw):
        indexlist = list(kw.keys())
        valuelist = list(kw.values())

        selectsql = 'select `%s`, %s from `%s`' % (cls.__primary_key__, ', '.join(cls.__fields__), cls.__table__)
        sql = '%s where %s' % (selectsql, ' and '.join("`%s`=?" % argv for argv in indexlist))
        rs = await select(sql, valuelist)
        if len(rs) == 0:
            return None
        return [cls(**r) for r in rs] #[cls(**r) for r in rs]
    @classmethod
    async def delete(cls, indexname, pk):
        ## find object by primary key
        #logger.info('【' + 'delete from %s where `%s`=%s' % (cls.__table__, indexname, pk) + '】')
        rows = await execute('delete from %s where `%s`=?' % (cls.__table__, indexname), [pk])
        if rows != 0:
            logger.info('delete by {}: affected rows: {}'.format(indexname, rows))
        if rows == 0:
            logger.warning('Fail to delete by {}: affected rows: {}'.format(indexname, rows))
    async def save(self):
        args = list(map(self.getValueOrDefault, self.__fields__))
        args.append(self.getValueOrDefault(self.__primary_key__))
        rows = await execute(self.__insert__, args)
        if rows != 1:
            logger.warning('failed to insert record: affected rows: %s' % rows)
            return
        return True

    async def saves(self, nums, savelist):

        args = list(map(self.getValueOrDefault, self.__fields__))
        args.append(self.getValueOrDefault(self.__primary_key__))
        escaped_fields = list(map(lambda f: '`%s`' % f, self.__fields__))
        str = self.__insert__
        for i in range(0, nums-1):
            if i == nums-1:
                str = str + (',(%s)') % create_args_string(len(escaped_fields) + 1)
            str = str + (',(%s)')%create_args_string(len(escaped_fields) + 1)
        rows = await execute(str, savelist)
        if rows == 0:
            logger.warning('failed to insert record: affected rows: %s' % rows)
            return
        else:
            logger.info('success to insert record: affected rows: %s' % rows)
        return True

    async def update(self):
        args = list(map(self.getValue, self.__fields__))
        args.append(self.getValue(self.__primary_key__))
        rows = await execute(self.__update__, args)
        if rows != 1:
            logger.warning('failed to update by primary key: affected rows: %s' % rows)

    async def remove(self):
        args = [self.getValue(self.__primary_key__)]
        rows = await execute(self.__delete__, args)
        if rows != 1:
            logger.warning('failed to remove by primary key: affected rows: %s' % rows)

    @classmethod
    async def updateitems(self, data = {}, **kw):
        if data:
            indexlist = list(data.keys())
            updatesql = 'update `%s` set %s' % (self.__table__, ' , '.join("`%s`=?" % argv for argv in indexlist))
            argvs = list(data.values())
            sql = '%s where %s' % (updatesql, ' and '.join("`%s`=?" % argv for argv in list(kw.keys())))
            argvs.extend(list(kw.values()))
            rows = await execute(sql, argvs)
            if rows != 1:
                logger.warning('failed to update by primary key: affected rows: %s' % rows)


    @classmethod
    async def finditems(cls, **kw):

        escaped_fields = list(map(lambda f: '`%s`' % f, cls.__fields__))

        indexlist = list(kw.keys())
        valuelist = list(kw.values())

        selectsql = 'select `%s`, %s from `%s`' % (cls.__primary_key__, ', '.join(escaped_fields), cls.__table__)
        sql = '%s where %s' % (selectsql, ' and '.join("`%s`=?" % argv for argv in indexlist))
        rs = await select(sql, valuelist)
        if len(rs) == 0:
            return None
        return [cls(**r) for r in rs]

class Field(object):

    def __init__(self, name, column_type, primary_key, default):
        self.name = name
        self.column_type = column_type
        self.primary_key = primary_key
        self.default = default

    def __str__(self):
        return '<%s, %s:%s>' % (self.__class__.__name__, self.column_type, self.name)

class StringField(Field):
    def __init__(self, name=None, primary_key=False, default=None, ddl='varchar(100)'):
        super().__init__(name, ddl, primary_key, default)

class BooleanField(Field):
    def __init__(self, name=None, default=False):
        super().__init__(name, 'boolean', False, default)

class IntegerField(Field):
    def __init__(self, name=None, primary_key=False, default=0):
        super().__init__(name, 'int', primary_key, default)

class FloatField(Field):
    def __init__(self, name=None, primary_key=False, default=0.0):
        super().__init__(name, 'real', primary_key, default)

class TextField(Field):
    def __init__(self, name=None, default=None):
        super().__init__(name, 'text', False, default)

class TimeField(Field):
    def __init__(self, name=None, default=None):
        super().__init__(name, 'TIMESTAMP', False, default)


if __name__ == '__main__':
    pass